import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
import time
#from datetime import datetime
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import matplotlib.animation as animation
from dev.T10 import T10
from SQL.T10 import T10 as t10_sql

class chartPageT10(object):
    def __init__(self, master=None,interval=1000):
        self.root = master
        print(self.root.baudrate)
        self.x = np.array([])
        self.y0 =self.y1=self.y2=self.y3 = np.array([])
        self.anim = None
        self.interval = interval
        #self.createPage()
    # 定义动态更新的数据函数
    def update_data(self):
        t10 = T10(self.root.port,self.root.baudrate,self.root.slave)
        # d = t10.read_random() # for test
        d = t10.read_reg()
        if d == []:
            self.anim.event_source.stop()
            showinfo(title='提示', message='无法读取数据')
        else:
            ts = t10_sql()
            ts.add([time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), d[0], d[1], d[2], d[3]])
            self.x = np.append(self.x, time.strftime('%H:%M:%S', time.localtime()))
            self.y0 = np.append(self.y0, d[0])
            self.y1 = np.append(self.y1, d[1])
            self.y2 = np.append(self.y2, d[2])
            self.y3 = np.append(self.y3, d[3])
            if len(self.y0) > 30:
                self.y0 = self.y0[1:]
                self.y1 = self.y1[1:]
                self.y2 = self.y2[1:]
                self.y3 = self.y3[1:]
                self.x = self.x[1:]
        return self.x, self.y0
    # 定义绘制图表的函数
    def plot_curve(self,frame):
        self.update_data()
        self.label_WBT.config(text='WBT:'+str(self.y0[-1])+'℃')
        self.label_Temperature.config(text='Temperature:'+str(self.y1[-1])+'℃')
        self.label_Humidity.config(text='Humidity:'+str(self.y2[-1])+'%')
        self.label_DBT.config(text='DBT:'+str(self.y3[-1])+'℃')
        self.ax.clear()  # 清除之前的图
        self.fig.autofmt_xdate(rotation=45)
        #self.ax.tick_params(axis='x', labelrotation=45)
        self.ax.plot(self.x,self.y0,marker = 'o',color = 'blue')  # 绘制新的图
        self.ax.plot(self.x,self.y1,marker = '*',color = 'red')  # 绘制新的图
        self.ax.plot(self.x,self.y2,marker = '+',color = 'green')  # 绘制新的图
        self.ax.plot(self.x,self.y3,marker = 'x',color = 'black')  # 绘制新的图
        # self.fig.legend(['WBT', 'Temperature','Humidity','DBT'], loc='lower right', facecolor='orange')
        self.ax.set_xlabel('Time(s)')
        # self.ax.set_ylabel('Temp(℃)')
        self.ax.set_title('SD123-T10 Real-time Data')
        self.ax.grid(True)
        self.canvas.draw()  # 重绘图表
    def createPage(self):
        self.newWindow = tk.Toplevel(self.root)
        self.newWindow.title("T10 Chart")
        self.newWindow.geometry("800x600")
        #self.label_title = tk.Label(self.newWindow, text='SD123-T10 实时数据',font=('SimHei',20))
        #self.label_title.pack(side=tk.TOP, fill=tk.X, expand=1)
        # 初始化Figure和FigureCanvas
        self.fig = Figure(figsize=(5, 5), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.newWindow)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        
        self.label_WBT = tk.Label(self.newWindow, text='WBT',font=('SimHei',16),fg='blue')
        self.label_WBT.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_Temperature = tk.Label(self.newWindow, text='Temperature',font=('SimHei',16),fg='red')
        self.label_Temperature.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_Humidity = tk.Label(self.newWindow, text='Humidity',font=('SimHei',16),fg='green')
        self.label_Humidity.pack(side=tk.LEFT, fill=tk.X, expand=1)
        self.label_DBT = tk.Label(self.newWindow, text='DBT',font=('SimHei',16),fg='black')
        self.label_DBT.pack(side=tk.LEFT, fill=tk.X, expand=1)
        # 创建一个图表和一个轴
        self.ax = self.fig.add_subplot(1,1,1)

        # 使用FuncAnimation来动态更新图表
        self.anim = animation.FuncAnimation(self.fig, self.plot_curve, frames=1, interval=self.interval,repeat_delay=self.interval)
if __name__ == '__main__':
    root = tk.Tk()
    root.title("Chart master")
    root.geometry("800x600")
    root.baudrate = 9600
    chart = chartPageT10(root,interval=1000)
    chart.createPage()
    root.mainloop()